import os

import requests

from common.common_tools import make_base_dirs, remove_temp_files
from common.hash_tools import md5


def download_and_cache(baseDir, prefix, url):
    filename = md5(url)
    local_file = "%s/%s/%s/%s%s" % (baseDir, prefix, filename[:2], filename, os.path.splitext(url)[1])
    if os.path.exists(local_file):
        return local_file
    else:
        try:
            make_base_dirs(local_file)
            print("download file, url: %s" % url)
            res = requests.get(url, timeout=60)
            with open(local_file, 'wb') as f:
                f.write(res.content)
            return local_file
        except Exception as e:
            remove_temp_files([local_file])
            raise e
